package userDao.UserImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import userDao.UserDbConnection.UserDbconnection;
import po.User;
import userDao.UserDao;
import view.LoginPanel;

public class UserImpl implements UserDao{
	private LoginPanel loginPanel;
	private User user;
	String sql = null;
	int result = 0;
	List<User> userList= new ArrayList<User>();
	@Override
	public List<User> findAll() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = UserDbconnection.getConnection();
			sql = "SELECT * FROM user";
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()) {
				String username = rs.getString(1);
				int password = rs.getInt(2);
				User us = new User(username,password);
				userList.add(us);
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			UserDbconnection.close(rs, ps);
		}
		return userList;
	}
	@Override
	public void save(User x) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			con = UserDbconnection.getConnection();
			sql = "INSERT INTO user VALUE(?,?)";
			ps = con.prepareStatement(sql);
			ps.setString(1,x.getUserName());
			ps.setInt(2, x.getPassword());
			result = ps.executeUpdate();
			System.out.println("操作结果是"+result+"：即注册成功");
		}catch(SQLException e) {
			e.printStackTrace();
		}finally{
			UserDbconnection.close(rs, ps);
		}
		
	}
	@Override
	public void delete(String x) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void update(User x) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public int getUserPassword(String x) {
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		int realPassword = 0;
		try {
			con = UserDbconnection.getConnection();
			sql = "SELECT user_password FROM user WHERE user_name=?";
			ps = con.prepareStatement(sql);	
			ps.setString(1, x);			
			rs = ps.executeQuery();
			while(rs.next()) {
				int password = rs.getInt(1);	
				realPassword = password;
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally{
			UserDbconnection.close(rs, ps);
		}
		return realPassword;
	}

}
